import queue
from queue import Queue
from threading import Event
import time
import os

# 隐藏pygame支持提示
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
import pygame
from pygame import mixer


class AudioPlayer:
    def __init__(
            self, 
            is_recording_event: Event, 
            playmusic_stopped_event: Event, 
            exit_event: Event, 
            playmusic_filename_queue: Queue,
            playeffect_filename_queue: Queue
            ):
        # 音频队列和停止事件
        self.is_recording_event = is_recording_event
        self.exit_event = exit_event
        self.playmusic_stopped_event = playmusic_stopped_event
        self.playmusic_filename_queue = playmusic_filename_queue
        self.playeffect_filename_queue = playeffect_filename_queue

        # 记录录音是否被中断
        self.was_interrupted = False

        # 初始化pygame音频混合器
        pygame.init()
        mixer.init()

        # 初始化成功
        self.playmusic_stopped_event.set()
        print("✅ 音频播放模块 \t| pygame \t→ 初始化成功")
        
    def _play_loop(self):
        """播放循环，处理队列中的音频文件"""
        while not self.exit_event.is_set():
            # 提示音循环
            try:
                # 注意一定不要阻塞
                filename = self.playeffect_filename_queue.get(block=False)
                mixer.Sound(filename).play()
                self.playeffect_filename_queue.task_done()
            except queue.Empty:
                pass

            if self.is_recording_event.is_set():
                if not self.was_interrupted:
                    self._clear_queue(self.playeffect_filename_queue)
                    self.playmusic_stopped_event.set()
                    self.was_interrupted = True
                time.sleep(0.02)
                continue
            else:
                self.was_interrupted = False

            try:
                # 使用非阻塞方式获取队列元素，设置超时避免无限阻塞
                filename = self.playmusic_filename_queue.get(timeout=0.02)

                # 在播放前再次检查录音状态
                if self.is_recording_event.is_set():
                    self._clear_queue(self.playmusic_filename_queue)
                    self.playmusic_stopped_event.set()
                    self.was_interrupted = True
                    continue

                # 加载并播放音频
                mixer.music.load(filename)
                mixer.music.play()

                # 播放过程中持续检查状态
                while mixer.music.get_busy():
                    if self.exit_event.is_set():
                        mixer.music.stop()
                        break
                    if self.is_recording_event.is_set():
                        mixer.music.stop()
                        # 加入延迟，防止其他线程在filename清空后又加入新的
                        time.sleep(0.15)
                        self._clear_queue(self.playmusic_filename_queue)
                        self.playmusic_stopped_event.set()
                        self.was_interrupted = True
                        break
                    time.sleep(0.02)

                # 播放完成后，标记任务完成
                self.playmusic_filename_queue.task_done()
            
            except queue.Empty:
                continue
                
        mixer.music.stop()
        self._clear_queue(self.playmusic_filename_queue)
        pygame.quit()

    def _clear_queue(self, queue: Queue):
        """清空队列中的所有音频文件"""
        while not queue.empty():
            try:
                queue.get_nowait()
                queue.task_done()
            except queue.Empty:
                break

    def start(self):
        """启动播放线程"""
        self._play_loop()


if __name__ == "__main__":
    pass
